package com.ellecity06.cwhiskymall.ui.consumer_gift

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.cwhiskymall.adapter.ReceiveRecordAdapter
import com.ellecity06.cwhiskymall.bean.response.ConsumerRecordResponse
import com.ellecity06.cwhiskymall.databinding.ActivityConsumerGiftBinding
import com.ellecity06.cwhiskymall.ui.MainActivity
import com.ellecity06.cwhiskymall.view.dialog.ReceiveConfirmDialog
import com.ellecity06.cwhiskymall.view.dialog.ReceiveResultDialog
import com.ellecity06.cwhiskymall.view.dialog.ReceiveSelectDialog
import com.gyf.immersionbar.ktx.immersionBar

/**
 * @author ellecity06
 * @time 2024/10/29 16:39
 * @des 消费赠送页面
 */
class ConsumerGiftActivity : BaseMvvmActivity<ActivityConsumerGiftBinding, ConsumerGiftViewModel>(),
    View.OnClickListener {
    private val recordAdapter: ReceiveRecordAdapter by lazy { ReceiveRecordAdapter() }
    private val levelList = mutableListOf(1796, 3592, 5388)
    private val giftList = mutableListOf(59.9, 119.7, 179.6)
    override val userBaseTitle: Boolean
        get() = false

    override fun inflateBinding(): ActivityConsumerGiftBinding {
        return ActivityConsumerGiftBinding.inflate(layoutInflater)
    }

    override val darkFont: Boolean
        get() = false

    override fun initialize(savedInstanceState: Bundle?) {
        statusBar(binding.statusBar)
        initView()
        fetchData()

    }

    private fun fetchData() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(ConsumerGiftIntent.FetchData)

        }
    }

    override fun initEvent() {
        binding.tvAdd.setOnClickListener(this)
        binding.ivBack.setOnClickListener(this)
    }

    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is ConsumerGiftState.RecordSuccess -> {
                    setData(it.data)
                }
                is ConsumerGiftState.ChangeBtnState -> {
                    setBtnState(it.receiveStatus)
                }
                is ConsumerGiftState.ToShopping -> {
                    goHome()
                }
                is ConsumerGiftState.ShowAlear -> {
                    ReceiveConfirmDialog(this, it.amount, onReceive = {
                        toReceive()
                    }, onToHome = {
                        goHome()
                    }).show()
                }
                is ConsumerGiftState.ShowResult -> {
                    ReceiveResultDialog(this, it.amount) {
                        fetchData()
                    }.show()

                }
                is ConsumerGiftState.SubReceiveSuccess -> {
                        fetchData()
                }
                is ConsumerGiftState.ShowSelect -> {
                    if (it.contriLevelId != null) {
                        // 弹窗选择升级贡献金
                        ReceiveSelectDialog(
                            this,
                            it.contriLevelId,
                            it.amount,
                            it.contribution
                        ) { id, level, isReceive ->
                            // 是否满足领取条件，满足则调用接口，不满足就是去首页消费
                            if (isReceive) {
                                lifecycleScope.launchWhenCreated {
                                    viewModel.intentChannel.send(
                                        ConsumerGiftIntent.SupReceive(
                                            id,
                                            level
                                        )
                                    )
                                }

                            } else {
                                goHome()
                            }

                        }.show()
                    }

                }
                else -> {}
            }
        }
    }


    private fun goHome() {
        MainActivity.launch(this)
        finish()
    }

    private fun toReceive(id: Int? = -1) {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(ConsumerGiftIntent.GoReceive(id))
        }
    }


    @SuppressLint("SetTextI18n")
    private fun setData(it: ConsumerRecordResponse) {
        binding.tvMax.text = "历史最高消费￥${it.maxLevel}"

        // 设置进度条
        binding.progress.setLevelInfo(it.totalAmount!!, levelList)
        binding.tvCon1.text = buildSpannedString {
            append("消费${levelList[0]}")
            color(Color.parseColor("#FED768")) {
                append("日领${giftList[0]}")
            }
        }
        binding.tvCon2.text = buildSpannedString {
            append("消费${levelList[1]}")
            color(Color.parseColor("#FED768")) {
                append("日领${giftList[1]}")
            }
        }
        binding.tvCon3.text = buildSpannedString {
            append("消费${levelList[2]}")
            color(Color.parseColor("#FED768")) {
                append("日领${giftList[2]}")
            }
        }
        // 根据数据状态设置按钮文字
        setBtnState(it.receiveStatus ?: 0)
        if (it.receiveRecordList != null && it.receiveRecordList.isNotEmpty()) {
            recordAdapter.submitList(it.receiveRecordList!!)

        } else {
            val list = mutableListOf<ConsumerRecordResponse.ReceiveRecord>()

            for (i in 1 until 31) {
                list.add(ConsumerRecordResponse.ReceiveRecord())
            }
            recordAdapter.submitList(list)
        }


    }

    private fun setBtnState(status: Int) {
        binding.tvAdd.text = if (status == 1) "消费增加进度" else "领取"
    }

    override fun initImmersionBar() {
        immersionBar {
            titleBar(binding.toolBar)
        }
    }

    private fun initView() {

        binding.rv.layoutManager = GridLayoutManager(this, 7)
        binding.rv.addGridDecoration()
        binding.rv.adapter = recordAdapter

        recordAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position)
            if (item?.receiveStatus == 0) {
                toReceive(item?.id)
            }


        }


    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.tvAdd.id -> {
                lifecycleScope.launchWhenCreated {
                    viewModel.intentChannel.send(ConsumerGiftIntent.AddBtnAction)
                }
            }
            binding.ivBack.id -> {
                finish()
            }
        }
    }
}